﻿// -----------------------------------------------------------------------
// <copyright company="Christoph van der Fecht - VDsoft">
// This code can be used in commercial, free and open source projects.
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using VDsoft.SeriesNewsReader.EventArguments;
using VDsoft.SeriesNewsReader.Model;
using GalaSoft.MvvmLight.Messaging;

namespace VDsoft.SeriesNewsReader
{
	/// <summary>
	/// Communication with the rss feed.
	/// </summary>
	public class RssLoader
	{
		/// <summary>
		/// Default instance of the <see cref="RssLoader"/> class.
		/// </summary>
		private static readonly RssLoader DefaultInstance = new RssLoader();

		/// <summary>
		/// Prevents a default instance of the <see cref="RssLoader"/> class from being created.
		/// </summary>
		private RssLoader()
		{ 
		}

		/// <summary>
		/// Gets the default instance of the <see cref="RssLoader"/> class.
		/// </summary>
		public static RssLoader Instance
		{
			get
			{
				return DefaultInstance;
			}
		}

		/// <summary>
		/// Loads all series and tv movies.
		/// </summary>
		public void LoadSeries()
		{
			WebClient client = new WebClient();
			client.DownloadStringCompleted += OnDownloadCompleted;
			client.DownloadStringAsync(new Uri("http://serienjunkies.org/xml/feeds/episoden.xml", UriKind.Absolute));
		}

		/// <summary>
		/// Parses the loaded data.
		/// </summary>
		/// <param name="sender">Object that raised the event.</param>
		/// <param name="e">Received data.</param>
		private void OnDownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
		{
			((WebClient)sender).DownloadStringCompleted -= this.OnDownloadCompleted;
			List<RssFeed> series = new List<RssFeed>();
			List<RssFeed> movies = new List<RssFeed>();
			List<string> languages = new List<string>();

			if (e.Error == null && e.Cancelled == false)
			{
				XElement xelement = XElement.Parse(e.Result);

				var items = xelement.Descendants(XName.Get("item"));

				foreach (var item in items)
				{
					var title = item.Descendants(XName.Get("title")).SingleOrDefault();
					string[] spliter = ((String)title.Value).Split(']');
					string seriesLanguage = spliter[0].Remove(0, 1);
					string seriesTitle = spliter[1].Replace('.', ' ').Trim();
					var link = item.Descendants(XName.Get("link")).SingleOrDefault();
					if (!link.Value.Contains("http://"))
					{
						link.Value = "http://" + link.Value;
					}

					Resolution currentRes = Resolution.Unknown;
					if (seriesTitle.Contains("720p"))
					{
						currentRes = Resolution.HDReady;
					}
					else if (seriesTitle.Contains("1080p"))
					{
						currentRes = Resolution.FullHD;
					}
					else
					{
						currentRes = Resolution.Unknown;
					}

					if (!languages.Contains(seriesLanguage) && !seriesLanguage.Equals("TV-FILM"))
					{
						languages.Add(seriesLanguage);
					}

					RssFeed feed = new RssFeed
					{
						Title = seriesTitle,
						Language = seriesLanguage,
						Link = new Uri(link.Value),
						Resolution = currentRes
					};

					if (feed.Language.ToUpper().Equals("TV-FILM"))
					{
						movies.Add(feed);
					}
					else
					{
						series.Add(feed);
					}
				}

				series = series.OrderBy(x => x.Title).ToList();
				movies = movies.OrderBy(x => x.Title).ToList();

				Messenger.Default.Send<List<RssFeed>>(series, ViewModel.ViewModelLocator.SeriesToken);
				Messenger.Default.Send<List<RssFeed>>(movies, ViewModel.ViewModelLocator.TvMovieToken);
				Messenger.Default.Send<List<string>>(languages.OrderBy(x => x).ToList(), ViewModel.ViewModelLocator.LanguageToken);
			}
		}
	}
}
